package com.warom.sdg.ui;

import android.app.Dialog;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.appcompat.app.AppCompatActivity;

import com.warom.sdg.R;
import com.warom.sdg.util.OpenApiExample;

public class GrainActivity extends AppCompatActivity {

    private ImageView screenshotImageView;
    private TextView statusTextView;
    private RadioGroup channelRadioGroup;
    private RadioGroup channelRadioGroup2;
    private Button wakeupButton;
    private Button screenshotButton;
    private Button liveStreamButton;
    
    // 视频播放相关
    private FrameLayout videoContainer;
    private VideoView videoView;
    private ImageButton fullscreenButton;
    private boolean isFullscreen = false;
    private String currentVideoUrl = null;
    
    // 设备信息 - 在实际应用中应该从配置或用户输入获取
    private static final String DEVICE_ID = "3a131a889160de64ptx9";
    private int selectedChannel = 0; // 默认选择通道0
    private static final String APP_KEY = "K35Y9D4F6H1B7V2M8";
    private static final String APP_SECRET = "5H2D8G4F7J1M6K3L9N5P2Q7R4S8V";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_grain);
        
        // 初始化视图
        initViews();
        
        // 设置通道选择监听器
        setupChannelSelectionListeners();
        
        // 设置按钮点击事件
        setupButtonListeners();
        
        // 设置全局错误监听
        setupErrorListener();
        
        // 应用启动时直接初始化API
        initApiDirectly();
    }
    
    /**
     * 应用启动时直接初始化API
     */
    private void initApiDirectly() {
        updateStatus("正在初始化API...");
        OpenApiExample.initOpenApi(GrainActivity.this, APP_KEY, APP_SECRET);
        updateStatus("API初始化完成，可以开始使用");
        Toast.makeText(GrainActivity.this, "API初始化完成", Toast.LENGTH_SHORT).show();
    }
    
    private void initViews() {
        screenshotImageView = findViewById(R.id.imageViewScreenshot);
        statusTextView = findViewById(R.id.textViewStatus);
        channelRadioGroup = findViewById(R.id.channelRadioGroup);
        channelRadioGroup2 = findViewById(R.id.channelRadioGroup2);
        wakeupButton = findViewById(R.id.buttonWakeup);
        screenshotButton = findViewById(R.id.buttonScreenshot);
        liveStreamButton = findViewById(R.id.buttonLiveStream);
        
        // 初始化视频播放相关视图
        videoContainer = findViewById(R.id.videoContainer);
        videoView = findViewById(R.id.videoView);
        fullscreenButton = findViewById(R.id.fullscreenButton);

        // 设置全屏按钮点击事件
        fullscreenButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleFullscreen();
            }
        });
        
        // 初始状态
        statusTextView.setText("准备就绪，请点击按钮执行操作");
        
        // 设置图片点击事件，点击后全屏查看
        screenshotImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 只有当图片有内容时才响应点击
                if (screenshotImageView.getDrawable() != null) {
                    showFullScreenImage();
                }
            }
        });
        
        android.util.Log.d("GrainActivity", "UI初始化完成");
    }
    
    /**
     * 显示全屏图片对话框
     */
    private void showFullScreenImage() {
        // 创建全屏对话框
        final Dialog dialog = new Dialog(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_fullscreen_image);
        
        // 获取对话框窗口并设置全屏
        Window window = dialog.getWindow();
        if (window != null) {
            window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
            window.setBackgroundDrawableResource(android.R.color.black);
        }
        
        // 获取对话框中的图片视图并设置图片
        ImageView fullscreenImageView = dialog.findViewById(R.id.fullscreenImageView);
        fullscreenImageView.setImageDrawable(screenshotImageView.getDrawable());
        
        // 设置点击关闭对话框
        fullscreenImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        
        // 显示对话框
        dialog.show();
        
        // 提示用户
        Toast.makeText(this, "点击图片返回", Toast.LENGTH_SHORT).show();
    }
    
    /**
     * 切换全屏/非全屏模式
     */
    private void toggleFullscreen() {
        if (isFullscreen) {
            // 退出全屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            
            // 恢复正常布局
            ViewGroup.LayoutParams params = videoContainer.getLayoutParams();
            params.height = getResources().getDimensionPixelSize(R.dimen.video_height);
            videoContainer.setLayoutParams(params);
            
            // 更新全屏按钮图标
            fullscreenButton.setImageResource(android.R.drawable.ic_menu_crop);
            
            isFullscreen = false;
        } else {
            // 进入全屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            
            // 设置全屏布局
            ViewGroup.LayoutParams params = videoContainer.getLayoutParams();
            params.height = ViewGroup.LayoutParams.MATCH_PARENT;
            videoContainer.setLayoutParams(params);
            
            // 更新全屏按钮图标
            fullscreenButton.setImageResource(android.R.drawable.ic_menu_close_clear_cancel);
            
            isFullscreen = true;
        }
    }
    
    /**
     * 设置通道选择监听器
     */
    private void setupChannelSelectionListeners() {
        // 第一组单选按钮（通道0-2）
        channelRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId != -1) {
                    // 清除第二组的选择
                    channelRadioGroup2.clearCheck();
                    
                    // 获取选中的通道
                    if (checkedId == R.id.radioChannel0) {
                        selectedChannel = 0;
                    } else if (checkedId == R.id.radioChannel1) {
                        selectedChannel = 1;
                    } else if (checkedId == R.id.radioChannel2) {
                        selectedChannel = 2;
                    }
                    
                    // 更新显示
                    updateStatus("已选择通道" + selectedChannel);
                }
            }
        });
        
        // 第二组单选按钮（通道3-4）
        channelRadioGroup2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId != -1) {
                    // 清除第一组的选择
                    channelRadioGroup.clearCheck();
                    
                    // 获取选中的通道
                    if (checkedId == R.id.radioChannel3) {
                        selectedChannel = 3;
                    } else if (checkedId == R.id.radioChannel4) {
                        selectedChannel = 4;
                    }
                    
                    // 更新显示
                    updateStatus("已选择通道" + selectedChannel);
                }
            }
        });
    }
    
    private void setupButtonListeners() {
        // 唤醒设备按钮
        wakeupButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                android.util.Log.d("GrainActivity", "唤醒设备按钮被点击");
                updateStatus("正在唤醒设备，通道" + selectedChannel + "...");
                OpenApiExample.wakeupDeviceExample(GrainActivity.this, DEVICE_ID, selectedChannel);
            }
        });
        
        // 获取截图按钮
        screenshotButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                android.util.Log.d("GrainActivity", "获取截图按钮被点击");
                updateStatus("正在获取设备截图，通道" + selectedChannel + "...");
                OpenApiExample.getDeviceScreenshotExample(GrainActivity.this, DEVICE_ID, selectedChannel, screenshotImageView);
            }
        });
        
        // 获取直播流按钮
        liveStreamButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                android.util.Log.d("GrainActivity", "获取直播流按钮被点击");
                updateStatus("正在获取直播流，通道" + selectedChannel + "...");
                // 直接在GrainActivity中处理直播流
                getLiveStream(DEVICE_ID, selectedChannel);
            }
        });
        
        android.util.Log.d("GrainActivity", "按钮监听器设置完成");
    }
    
    /**
     * 获取直播流并播放
     * @param deviceId 设备ID
     * @param channel 通道号
     */
    private void getLiveStream(final String deviceId, final int channel) {
        // 获取设备管理器实例
        OpenApiExample.getLiveStreamUrl(this, deviceId, channel, new OpenApiCallback() {
            @Override
            public void onSuccess(String liveStreamUrl) {
                // 保存当前视频URL
                currentVideoUrl = liveStreamUrl;
                
                // 显示视频容器
                videoContainer.setVisibility(View.VISIBLE);
                
                // 设置媒体控制器
                MediaController mediaController = new MediaController(GrainActivity.this);
                mediaController.setAnchorView(videoView);
                videoView.setMediaController(mediaController);
                
                // 设置视频源
                videoView.setVideoURI(Uri.parse(liveStreamUrl));
                
                // 设置准备完成监听器
                videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        // 开始播放
                        videoView.start();
                        updateStatus("直播流播放中");
                    }
                });
                
                // 设置错误监听器
                videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                    @Override
                    public boolean onError(MediaPlayer mp, int what, int extra) {
                        updateStatus("视频播放错误: " + what + ", " + extra);
                        return false;
                    }
                });
                
                // 设置完成监听器
                videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        updateStatus("视频播放完成");
                    }
                });
            }
            
            @Override
            public void onFailure(String errorMessage) {
                updateStatus("获取直播流失败: " + errorMessage);
                Toast.makeText(GrainActivity.this, "获取直播流失败: " + errorMessage, Toast.LENGTH_LONG).show();
            }
        });
    }
    
    /**
     * 设置全局错误监听
     */
    private void setupErrorListener() {
        // 这里可以添加全局的错误处理逻辑
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable ex) {
                updateStatus("发生错误: " + ex.getMessage());
            }
        });
    }
    
    /**
     * 更新状态文本
     * 
     * @param status 状态信息
     */
    public void updateStatus(final String status) {
        // 确保在UI线程更新UI
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                statusTextView.setText(status);
            }
        });
    }
    
    @Override
    public void onBackPressed() {
        if (isFullscreen) {
            // 如果是全屏模式，先退出全屏
            toggleFullscreen();
        } else {
            super.onBackPressed();
        }
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        // 暂停视频播放
        if (videoView != null && videoView.isPlaying()) {
            videoView.pause();
        }
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        // 恢复视频播放
        if (videoView != null && currentVideoUrl != null) {
            videoView.resume();
        }
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 停止视频播放
        if (videoView != null) {
            videoView.stopPlayback();
        }
    }
    
    /**
     * 回调接口，用于处理直播流URL获取结果
     */
    public interface OpenApiCallback {
        void onSuccess(String liveStreamUrl);
        void onFailure(String errorMessage);
    }
}